import http from 'axios';
import Qs from 'qs'
import HttpUtil from './util'
import { HttpStatus } from "@/utils/enums/HttpStatus";
// 设置默认请求地址
const httpUtil = new HttpUtil();
const request = http.create({
    baseURL: httpUtil.baseURL,
})

request.interceptors.request.use((config) => {
    if (config.method == 'post') {
        const default_sign = HttpUtil.default_sign;
        let temp;
        if ((config as any).headers['Content-Type'] === 'multipart/form-data') {
            temp = { ...default_sign, security_key: HttpUtil.security_key };
            const f = new FormData();
            f.append('file', config.data.file.get('file'));
            for (let key in HttpUtil.default_sign) {
                f.append(key, default_sign[key]);
            }
            f.append('sign', HttpUtil.create_sign(temp));
            config.data = f;
            return config;
        }

        (config as any).headers['Content-Type'] = 'application/x-www-form-urlencoded';
        //  特殊处理null
        for (const attr in config.data) {
            if (config.data[attr] === null) {
                delete config.data[attr];
                continue;
            }
        }
        temp = { ...config.data, ...default_sign, security_key: HttpUtil.security_key };
        config.data = Qs.stringify({
            ...config.data,
            ...default_sign,
            sign: HttpUtil.create_sign(temp),
        });
    }
    return config;
}, (error) => {
    Promise.reject(error);
})

request.interceptors.response.use((response) => {
    const { data } = response;
    if (data.iRet = HttpStatus.SUCCESS) {
        return response;
    }
}, (error) => {
    Promise.reject(error);
})